const axios = require('axios');
const https = require('https');

class ApiHealthChecker {
  constructor() {
    this.healthStatus = new Map();
    this.lastCheck = new Map();
    this.checkInterval = 5 * 60 * 1000; // 5分钟检查间隔
  }

  // 检查API健康状态
  async checkApiHealth(apiUrl, timeout = 5000) {
    const now = Date.now();
    const lastCheckTime = this.lastCheck.get(apiUrl) || 0;
    
    // 如果最近检查过，直接返回缓存状态
    if (now - lastCheckTime < this.checkInterval) {
      return this.healthStatus.get(apiUrl) || false;
    }

    try {
      const response = await axios.get(apiUrl, {
        timeout,
        headers: {
          'User-Agent': 'Mozilla/5.0 (compatible; HealthChecker/1.0)',
        },
        httpsAgent: new https.Agent({ 
          rejectUnauthorized: false,
          timeout: timeout
        })
      });

      const isHealthy = response.status === 200 && response.data;
      this.healthStatus.set(apiUrl, isHealthy);
      this.lastCheck.set(apiUrl, now);
      
      console.log(`API健康检查 ${apiUrl}: ${isHealthy ? '正常' : '异常'}`);
      return isHealthy;
      
    } catch (error) {
      console.warn(`API健康检查失败 ${apiUrl}:`, error.message);
      this.healthStatus.set(apiUrl, false);
      this.lastCheck.set(apiUrl, now);
      return false;
    }
  }

  // 获取所有健康的API
  async getHealthyApis(apiList) {
    const results = await Promise.allSettled(
      apiList.map(api => this.checkApiHealth(api.url, api.timeout))
    );
    
    return apiList.filter((api, index) => {
      const result = results[index];
      return result.status === 'fulfilled' && result.value === true;
    });
  }

  // 清除缓存
  clearCache() {
    this.healthStatus.clear();
    this.lastCheck.clear();
  }

  // 获取健康状态报告
  getHealthReport() {
    const report = {};
    for (const [url, status] of this.healthStatus.entries()) {
      report[url] = {
        healthy: status,
        lastCheck: new Date(this.lastCheck.get(url)).toISOString()
      };
    }
    return report;
  }
}

module.exports = new ApiHealthChecker();